import 'package:flutter/material.dart';
import 'theory_edit_page.dart';
import '../models/theory_model.dart';
import 'theory_detail_page.dart';
import '../models/db_helper.dart';

class TheoryPage extends StatefulWidget {
  const TheoryPage({super.key});

  @override
  State<TheoryPage> createState() => _TheoryPageState();
}

class _TheoryPageState extends State<TheoryPage> {
  List<TheoryContent> theoryList = [];
  String _search = '';
  bool _showFavoriteOnly = false;
  bool _showNoteOnly = false;

  @override
  void initState() {
    super.initState();
    _loadTheoryList();
  }

  Future<void> _loadTheoryList() async {
    final data = await DBHelper.getAllTheory();
    setState(() {
      theoryList = data.map((e) => TheoryContent.fromMap(e)).toList();
    });
  }

  Future<void> _addTheory(TheoryContent content) async {
    await DBHelper.insertTheory(content.toMap());
    await _loadTheoryList();
  }

  Future<void> _editTheory(TheoryContent content) async {
    await DBHelper.updateTheory(content.toMap());
    await _loadTheoryList();
  }

  List<TheoryContent> get _filteredList {
    List<TheoryContent> list = theoryList;
    if (_showFavoriteOnly) {
      list = list.where((item) => item.isFavorite).toList();
    }
    if (_showNoteOnly) {
      list = list.where((item) => (item.note != null && item.note!.isNotEmpty)).toList();
    }
    if (_search.isNotEmpty) {
      final q = _search.toLowerCase();
      list = list.where((item) {
        return item.jing.toLowerCase().contains(q) ||
          item.summary.toLowerCase().contains(q) ||
          item.pathogenesis.toLowerCase().contains(q) ||
          item.symptoms.toLowerCase().contains(q) ||
          item.therapy.toLowerCase().contains(q) ||
          item.formula.toLowerCase().contains(q);
      }).toList();
    }
    return list;
  }

  // 获取最近学习内容
  List<TheoryContent> get _recentStudyList {
    final list = List<TheoryContent>.from(theoryList);
    list.removeWhere((e) => e.lastStudyTime == null);
    list.sort((a, b) => b.lastStudyTime!.compareTo(a.lastStudyTime!));
    return list.take(3).toList();
  }

  void _openDetail(TheoryContent content) async {
    final updated = TheoryContent(
      id: content.id,
      jing: content.jing,
      summary: content.summary,
      pathogenesis: content.pathogenesis,
      symptoms: content.symptoms,
      therapy: content.therapy,
      formula: content.formula,
      isFavorite: content.isFavorite,
      hasNote: content.hasNote,
      isKey: content.isKey,
      progress: content.progress,
      lastStudyTime: DateTime.now(),
      note: content.note,
    );
    await DBHelper.updateTheory(updated.toMap());
    await _loadTheoryList();
    content = updated;
    if (!mounted) return;
    await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => TheoryDetailPage(content: content),
      ),
    );
    await _loadTheoryList();
  }

  void _startLearning() {
    int idx = _filteredList.indexWhere((e) => e.progress < 1.0);
    if (idx == -1) idx = 0;
    if (_filteredList.isNotEmpty) {
      _openDetail(_filteredList[idx]);
    }
  }

  // 计算六经进度
  Map<String, double> get _jingProgressMap {
    final jingList = ['太阳经', '阳明经', '少阳经', '太阴经', '少阴经', '厥阴经'];
    Map<String, List<TheoryContent>> group = {for (var j in jingList) j: []};
    for (var item in theoryList) {
      if (group.containsKey(item.jing)) {
        group[item.jing]!.add(item);
      }
    }
    Map<String, double> result = {};
    for (var j in jingList) {
      final list = group[j]!;
      if (list.isEmpty) {
        result[j] = 0.0;
      } else {
        result[j] = list.map((e) => e.progress).fold(0.0, (a, b) => a + b) / list.length;
      }
    }
    return result;
  }

  void _toggleFavoriteFilter() {
    setState(() {
      _showFavoriteOnly = !_showFavoriteOnly;
      if (_showFavoriteOnly) _showNoteOnly = false;
    });
  }

  void _toggleNoteFilter() {
    setState(() {
      _showNoteOnly = !_showNoteOnly;
      if (_showNoteOnly) _showFavoriteOnly = false;
    });
  }

  void _showRelationGraph() {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) {
        return Container(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('知识点关联图', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18, color: Colors.brown)),
              const SizedBox(height: 16),
              // 静态示意图，可后续替换为动态
              Image.asset('assets/knowledge_graph_demo.png', height: 180, fit: BoxFit.contain),
              const SizedBox(height: 12),
              const Text('本图展示六经理论、病机、症状、方剂等知识点之间的关联关系。后续可扩展为动态交互式知识图谱。', style: TextStyle(color: Colors.brown)),
            ],
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('理论学习'),
        backgroundColor: Colors.brown[50],
        elevation: 0,
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 搜索栏及功能按钮
              Row(
                children: [
                  Expanded(
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                      decoration: BoxDecoration(
                        color: Colors.brown[50],
                        borderRadius: BorderRadius.circular(24),
                      ),
                      child: Row(
                        children: [
                          const Icon(Icons.search, color: Colors.brown),
                          const SizedBox(width: 8),
                          Expanded(
                            child: TextField(
                              decoration: const InputDecoration(
                                hintText: '搜索经理论知识、病机、方剂...',
                                border: InputBorder.none,
                                isDense: true,
                              ),
                              style: const TextStyle(color: Colors.brown),
                              onChanged: (v) => setState(() => _search = v),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  IconButton(
                    icon: Icon(Icons.star, color: _showFavoriteOnly ? Colors.amber[700] : Colors.brown),
                    tooltip: _showFavoriteOnly ? '显示全部' : '仅看收藏',
                    onPressed: _toggleFavoriteFilter,
                  ),
                  IconButton(
                    icon: Icon(Icons.note, color: _showNoteOnly ? Colors.brown : Colors.brown[200]),
                    tooltip: _showNoteOnly ? '显示全部' : '仅看有笔记',
                    onPressed: _toggleNoteFilter,
                  ),
                  IconButton(
                    icon: Icon(Icons.graphic_eq, color: Colors.teal),
                    tooltip: '知识点关联图',
                    onPressed: _showRelationGraph,
                  ),
                ],
              ),
              const SizedBox(height: 24),
              // 六经分类进度
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _JingProgress(name: '太阳经', percent: _jingProgressMap['太阳经'] ?? 0.0, color: Color(0xFFD2A06B), icon: Icons.wb_sunny),
                        SizedBox(height: 16),
                        _JingProgress(name: '少阳经', percent: _jingProgressMap['少阳经'] ?? 0.0, color: Color(0xFFF6D365), icon: Icons.flash_on),
                        SizedBox(height: 16),
                        _JingProgress(name: '少阴经', percent: _jingProgressMap['少阴经'] ?? 0.0, color: Color(0xFFB39DDB), icon: Icons.nightlight_round),
                      ],
                    ),
                  ),
                  const SizedBox(width: 32),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _JingProgress(name: '阳明经', percent: _jingProgressMap['阳明经'] ?? 0.0, color: Color(0xFF80CBC4), icon: Icons.opacity),
                        SizedBox(height: 16),
                        _JingProgress(name: '太阴经', percent: _jingProgressMap['太阴经'] ?? 0.0, color: Color(0xFF90CAF9), icon: Icons.waves),
                        SizedBox(height: 16),
                        _JingProgress(name: '厥阴经', percent: _jingProgressMap['厥阴经'] ?? 0.0, color: Color(0xFF8D6E63), icon: Icons.bubble_chart),
                      ],
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 32),
              // 六经理论内容卡片
              ListView(
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                children: _filteredList.map((item) => _TheoryCard(
                  jing: item.jing,
                  summary: item.summary,
                  pathogenesis: item.pathogenesis,
                  symptoms: item.symptoms,
                  therapy: item.therapy,
                  formula: item.formula,
                  progress: item.progress,
                  isFavorite: item.isFavorite,
                  hasNote: item.hasNote,
                  isKey: item.isKey,
                  onEdit: () async {
                    await Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (_) => TheoryEditPage(content: item, onSave: _editTheory),
                      ),
                    );
                  },
                  onTap: () => _openDetail(item),
                )).toList(),
              ),
              const SizedBox(height: 32),
              // 最近学习
              const Text('最近学习', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.brown)),
              const SizedBox(height: 16),
              ..._recentStudyList.map((item) => _RecentStudyItem(
                title: item.summary.isNotEmpty ? '${item.jing} - ${item.summary}' : item.jing,
                time: item.lastStudyTime != null ? '${item.lastStudyTime!.hour.toString().padLeft(2, '0')}:${item.lastStudyTime!.minute.toString().padLeft(2, '0')}' : '',
                icon: Icons.menu_book,
                onTap: () => _openDetail(item),
              )),
              const SizedBox(height: 32),
              // 推荐学习
              const Text('推荐学习', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.brown)),
              const SizedBox(height: 16),
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.brown[50],
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: const [
                    Text('六经辨证核心理论', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15)),
                    SizedBox(height: 8),
                    Text('本章节将系统讲解胡希恕六经辨证的理论体系，包括六经分类、病机特点、典型方剂、症状表现、方证对应内容，是理解整体辨证体系的基础。'),
                  ],
                ),
              ),
              const SizedBox(height: 32),
              // 开始学习按钮
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.brown,
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                    padding: const EdgeInsets.symmetric(vertical: 16),
                  ),
                  onPressed: _startLearning,
                  child: const Text('开始学习', style: TextStyle(fontSize: 16, color: Colors.black)),
                ),
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.brown,
        child: const Icon(Icons.add, color: Colors.white),
        onPressed: () async {
          await Navigator.of(context).push(
            MaterialPageRoute(
              builder: (_) => TheoryEditPage(onSave: _addTheory),
            ),
          );
        },
      ),
    );
  }
}

class _JingProgress extends StatelessWidget {
  final String name;
  final double percent;
  final Color color;
  final IconData icon;
  const _JingProgress({required this.name, required this.percent, required this.color, required this.icon});

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        CircleAvatar(
          backgroundColor: color.withAlpha((0.2 * 255).toInt()),
          child: Icon(icon, color: color),
        ),
        const SizedBox(width: 12),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(name, style: const TextStyle(fontWeight: FontWeight.bold)),
            Text('学习进度 ${(percent * 100).toInt()}%', style: const TextStyle(fontSize: 12, color: Colors.brown)),
          ],
        ),
        const SizedBox(width: 12),
        Expanded(
          child: LinearProgressIndicator(
            value: percent,
            minHeight: 8,
            backgroundColor: color.withAlpha((0.1 * 255).toInt()),
            valueColor: AlwaysStoppedAnimation<Color>(color),
          ),
        ),
      ],
    );
  }
}

class _RecentStudyItem extends StatelessWidget {
  final String title;
  final String time;
  final IconData icon;
  final VoidCallback? onTap;
  const _RecentStudyItem({required this.title, required this.time, required this.icon, this.onTap});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Row(
        children: [
          CircleAvatar(
            backgroundColor: Colors.brown[100],
            child: Icon(icon, color: Colors.brown),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(title, style: const TextStyle(fontWeight: FontWeight.bold)),
                Text('上次学习: $time', style: const TextStyle(fontSize: 12, color: Colors.brown)),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _TheoryCard extends StatelessWidget {
  final String jing;
  final String summary;
  final String pathogenesis;
  final String symptoms;
  final String therapy;
  final String formula;
  final double progress;
  final bool isFavorite;
  final bool hasNote;
  final bool isKey;
  final VoidCallback? onEdit;
  final VoidCallback? onTap;
  const _TheoryCard({
    required this.jing,
    required this.summary,
    required this.pathogenesis,
    required this.symptoms,
    required this.therapy,
    required this.formula,
    required this.progress,
    this.isFavorite = false,
    this.hasNote = false,
    this.isKey = false,
    this.onEdit,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Card(
        margin: const EdgeInsets.symmetric(vertical: 8),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        elevation: 1,
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(jing, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: Colors.brown)),
                  const SizedBox(width: 8),
                  if (isFavorite) Icon(Icons.star, color: Colors.amber[700], size: 18),
                  if (hasNote) Icon(Icons.note, color: Colors.brown, size: 18),
                  if (isKey) Container(
                    margin: const EdgeInsets.only(left: 4),
                    padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    decoration: BoxDecoration(
                      color: Colors.red[100],
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: const Text('重点', style: TextStyle(fontSize: 12, color: Colors.red)),
                  ),
                  if (progress >= 1.0)
                    Container(
                      margin: const EdgeInsets.only(left: 4),
                      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                      decoration: BoxDecoration(
                        color: Colors.green[100],
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: const Text('已学', style: TextStyle(fontSize: 12, color: Colors.green)),
                    ),
                  const Spacer(),
                  if (onEdit != null)
                    IconButton(
                      icon: const Icon(Icons.edit, color: Colors.brown),
                      tooltip: '编辑',
                      onPressed: onEdit,
                    ),
                  SizedBox(
                    height: 32,
                    child: TextButton.icon(
                      style: TextButton.styleFrom(
                        backgroundColor: Colors.brown[50],
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                        padding: const EdgeInsets.symmetric(horizontal: 12),
                      ),
                      icon: const Icon(Icons.play_arrow, color: Colors.brown, size: 18),
                      label: const Text('学习', style: TextStyle(color: Colors.brown, fontSize: 14)),
                      onPressed: onTap,
                    ),
                  ),
                  SizedBox(
                    width: 80,
                    child: LinearProgressIndicator(
                      value: progress,
                      minHeight: 8,
                      backgroundColor: Colors.brown.withAlpha((0.1 * 255).toInt()),
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.brown),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Text('概述：$summary'),
              Text('病机：$pathogenesis'),
              Text('症状：$symptoms'),
              Text('治法：$therapy'),
              Text('方剂：$formula'),
            ],
          ),
        ),
      ),
    );
  }
} 